<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="8" :xs="24">
        <div class="head-container">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            label-width="120px"
            label-position="left">
            <el-form-item label="Name" prop="userName">
              <el-input
                v-model="queryParams.userName"
                placeholder=""
                clearable
                style="width: 200px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="Email" prop="phonenumber">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder=""
                clearable
                style="width: 200px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="Phone" prop="phonenumber">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder=""
                clearable
                style="width: 200px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="Education" prop="phonenumber">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder=""
                clearable
                style="width: 200px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label-width="120px" label="Job deseription" prop="phonenumber">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder=""
                clearable
                style="width: 200px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>

            <el-form-item style="width: 100%;display: flex;justify-content: center;">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                style="width: 200px;"
                @click="handleQuery">搜索</el-button>
              <!--<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
            </el-form-item>
          </el-form>
        </div>
        <div class="head-container">
          <el-table
            :row-style="isRed"
            :show-header="false"
            v-loading="loading"
            :data="candidateList"
          >
            <el-table-column
              label="Email"
              align="center">
              <template slot-scope="scope">
                <div @click="handleEdit(scope.row)" style="
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;
                height: 40px;">
                  <span>{{scope.row.email1}}</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            small
            layout="prev, pager, next"
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getCVList"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="16" :xs="24" style="border-left: 1px solid #cccccc;">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-position="left"
          style="padding-left: 10px;padding-right: 10px;">
          <el-row>
            <el-col :span="24">
              <div>
                <span style="color: #000;font-weight: bold;">基本信息</span>
              </div>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px;">
            <el-col :span="12">
              <el-form-item label-width="60px" label="Name" prop="name">
                <el-input v-model="form.name" placeholder="" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Gender" prop="gender" style="margin-left: 10px;">
                <el-select v-model="form.gender" placeholder="请选择性别">
                  <el-option
                    v-for="dict in dict.type.sys_user_sex"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label-width="60px" label="District" prop="district">
                <el-input v-model="form.district" placeholder="" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="60px" label="Birth" prop="birthyear" style="margin-left: 10px;">
                <el-date-picker
                  v-model="form.birthyear"
                  value-format="yyyy"
                  type="year"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label-width="60px" label="Email" prop="email1">
                <el-input v-model="form.email1" placeholder="" style="" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="60px" label="Phone" prop="phone1" style="margin-left: 10px;">
                <el-input v-model="form.phone1" placeholder="" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>

          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="Expect Salary" prop="email1">
                <el-input v-model="form.salary" placeholder="" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="Job function" prop="jobFunction">
                <el-input v-model="form.jobFunction" placeholder="" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px;">
            <el-col :span="12">
              <el-upload
                :action="uploadUrl"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                accept=".pdf,.doc,.docx"
                name="file"
                :headers="headers"
                multiple
                :limit="100"
                ref="upload"
                :on-exceed="handleExceed"
                :on-success="handleFileSuccess"
                :file-list="form.fileList">
                <div style="display: flex;align-items: center;">
                  <i class="el-icon-upload" style="font-size: 35px;"></i>
                  <span style="color: #99a9bf;font-size: 15px;margin-left: 2px;">Upload</span>
                </div>
                <!--<el-button size="small" type="primary">点击上传</el-button>-->
                <div slot="tip" class="el-upload__tip">只能上传pdf/word文件</div>
              </el-upload>
            </el-col>
          </el-row>

          <div style="margin-top: 50px;">
            <span style="color: #000;font-weight: bold;">工作经验</span>
            <div style="margin-top: 20px;">
              <el-form v-for=" (item,index) in form.ccompanyList"
                       :key="index" :model="item" :ref="'formData'+index"
                       label-width="80px"
                       style="border-bottom: 2px dotted #cccccc;margin-top: 10px">
                <div style="display: inline-flex;flex-direction: row-reverse;width: 100%;">
                  <el-button
                    @click="removeJobs(index)"
                    type="danger"
                    icon="el-icon-delete"
                    circle size="mini"></el-button>
                </div>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="Company" prop="com">
                      <el-input v-model="item.com" placeholder="" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="Title" prop="title">
                      <el-input v-model="item.title" placeholder="" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="Start Date">
                      <el-date-picker
                        v-model="item.startTime"
                        value-format="yyyy-MM"
                        type="month"
                      ></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="End Date">
                      <el-date-picker
                        v-model="item.endTime"
                        value-format="yyyy-MM"
                        type="month"
                      ></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label-width="80px" label="description">
                      <editor v-model="item.description" :min-height="392"/>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <el-button type="primary" round style="font-size: 12px;padding: 8px 12px;margin-top: 10px;" @click="addJobs">+Add New</el-button>
          </div>
          <div style="margin-top: 50px;">
            <span style="color: #000;font-weight: bold;">Education</span>
            <div style="margin-top: 20px;">
              <el-form v-for=" (item,index) in form.schoolList"
                       :key="index" :model="item" :ref="'formData'+index"
                       label-width="80px"
                       style="border-bottom: 2px dotted #cccccc;margin-top: 10px">
                <div style="display: inline-flex;flex-direction: row-reverse;width: 100%;">
                  <el-button
                    @click="removeSchool(index)"
                    type="danger"
                    icon="el-icon-delete"
                    circle size="mini"></el-button>
                </div>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="School" prop="name">
                      <el-input v-model="item.name" placeholder="" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="Major" prop="major">
                      <el-input v-model="item.major" placeholder="" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="Degree" prop="degree">
                      <el-input v-model="item.degree" placeholder="" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="Start Date">
                      <el-date-picker
                        v-model="item.startTime"
                        value-format="yyyy-MM"
                        type="month"
                      ></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="End Date">
                      <el-date-picker
                        v-model="item.endTime"
                        value-format="yyyy-MM"
                        type="month"
                      ></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label-width="80px" label="description">
                      <editor v-model="item.description" :min-height="392"/>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <el-button type="primary" round style="font-size: 12px;padding: 8px 12px;margin-top: 10px;" @click="addSchool">+Add New</el-button>
          </div>
          <el-row>
            <p style="color: #000;font-weight: bold;margin-top: 50px;">Other</p>
            <el-col :span="24" style="margin-top: 10px;">
              <el-form-item label-width="0" label="">
                <editor v-model="form.other" :min-height="392"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import { listCandidate, getCandidate, delCandidate, addCandidate, updateCandidate } from "@/api/system/candidate";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: { Treeselect },
  data() {
    return {
      loading: false,
      jobsData: {
        id: null,
        cid: null,
        com: null,
        title: null,
        startTime: null,
        endTime: null,
        description: null
      },
      schoolDate: {
        id: null,
        name: null,
        major: null,
        degree: null,
        description: null,
        startTime: null,
        endTime: null
      },
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      candidateList: [],
      candidateList2: [],
      // 弹出层标题
      title: "",
      uploadUrl: "http://jobslink.megaslink.com/prod-api" + "/common/upload", // process.env.VUE_APP_BASE_API上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      selectedArrData: [], // 把选择到的当前行的id存到数组中
      queryParams2: {
        id: null
      },
      // 查询参数
      queryParams: {
        id: null,
        pageNum: 1,
        pageSize: 10,
        email1: null,
        email2: null,
        name: null,
        phone1: null,
        phone2: null,
        gender: null,
        salary: null,
        education: null,
        other: null,
        district: null,
        age: null,
        birthyear: null
      },
      // 表单参数
      fileData: {name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'},
      // 表单参数
      form: {
        id: null,
        email1: null,
        email2: null,
        name: null,
        phone1: null,
        phone2: null,
        gender: null,
        salary: null,
        education: null,
        other: null,
        district: null,
        age: null,
        birthyear: null,
        filePath: null,
        fileList: [],
        ccompanyList: [
          {
            id: null,
            cid: null,
            com: null,
            title: null,
            startTime: null,
            endTime: null,
            description: null
          }
        ],
        schoolList: [
          {
            id: null,
            name: null,
            major: null,
            degree: null,
            description: null,
            startTime: null,
            endTime: null
          }
        ]
      },
      // 表单校验
      rules: {
        email1: [
          { required: true, message: "email is null", trigger: "blur" }
        ],
        name: [
          { required: true, message: "name is null", trigger: "blur" }
        ],
        phone1: [
          { required: true, message: "phone is null", trigger: "blur" }
        ],
      },
    };
  },
  created() {
    this.getCVList();
  },
  methods: {
    //编辑事件
    handleEdit(row){
      console.log("====================================")
      this.queryParams2.id = row.id;
      this.getList();
      console.log("======qqqqqqqqq==============================")
      this.selectedArrData = [row];
    },
    isRed({ row }) {
      const checkIdList = this.selectedArrData.map((item) => item.id);
      if (checkIdList.includes(row.id)) {
        return {
          backgroundColor: "#DE6",
          // color: "red",
        };
      }
    },
    cvdetail(data) {
      this.queryParams2.id = data;
      this.getList();
    },
    getCVList() {
      this.loading = true;
      listCandidate(this.queryParams).then(response => {
        this.candidateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取pdf总页数
    getTotal() {
      // 多页pdf的src中不能直接使用后端获取的pdf地址 否则会按页数请求多次数据
      // 需要使用下述方法的返回值作为url
      this.pdfUrl = pdf.createLoadingTask(this.form.filePath)
      // 获取页码
      this.pdfUrl.promise.then(pdf => this.pageTotal = pdf.numPages).catch(error => {})
    },
    removeSchool(index) {
      if (this.form.schoolList.length <= 1) {
        this.$modal.msgError("最少保留一个");
        return;
      }
      this.form.schoolList.splice(index2, 1);
    },
    removeJobs(index) {
      if (this.form.ccompanyList.length <= 1) {
        this.$modal.msgError("最少保留一个");
        return;
      }
      this.form.ccompanyList.splice(index2, 1);
    },
    addSchool() {
      this.form.schoolList.push(this.schoolDate);
    },
    addJobs() {
      this.form.ccompanyList.push(this.jobsData);
    },
    handleRemove(file, fileList) {
      console.log(file);
      console.log(fileList);
      if (file.status == "success") {
        this.form.fileList = this.form.fileList.filter(item => {
          return !(item.name == file.name && item.url == file.url);
        } );
      }
      console.log(this.form.fileList);
    },
    handlePreview(file) {
      console.log(file);
      // 截取上传文件的后缀名
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      console.log(fileType);
      // 判断文件名的类型，允许多种就判断多个
      if (fileType.toLocaleLowerCase() == 'pdf' || fileType.toLocaleLowerCase() == 'doc' || fileType.toLocaleLowerCase() == 'docx') {
        // if (fileType.toLocaleLowerCase() == 'pdf') {
        //   this.getTotal();
        //   this.openFile = true;
        // }  else {
        //   window.open('http://www.megaslink.com:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(this.form.filePath)));
        // }
        let Base64 = require('js-base64').Base64
        window.open('http://www.megaslink.com:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(this.form.filePath)));
      } else {
        this.$message.warning("文件类型必须为pdf,doc,docx格式")
        // 返回false 就不会执行上传操作了
        return false
      }
    },
    // 只能上传单个文件，选择文件覆盖原有文件
    // changeUpload(file, fileList) {
    //   if (fileList.length > 1 && file.status !== "fail") {
    //     fileList.splice(0, 1);
    //     // 多选并上传多个文件：
    //     // 方法一：fileList.splice(0, n)。n:多选文件的数量。--数组从前往后顺序截取。
    //     // 方法二：fileList.splice(0, -n)。n:多选文件的数量。--数组从后往前顺序截取（保留最新上传的，截去之前上传的。--方法一反之）
    //   } else if (file.status === "fail") {
    //     this.$message.warning("上传失败，请重新上传！");
    //     fileList.splice(0, 1);
    //   }
    // },
    handleExceed(files, fileList) {
      // this.$message.warning(`当前限制只能上传 1 个文件或者删除重新上传`);
    },
    handleFileSuccess(response, file, fileList) {
      console.log(response);
      console.log(file);
      console.log(fileList);
      if (response.code == 200) {
        console.log("================" + response.url);
        this.form.filePath = response.url;
        this.form.fileList.push( {
            name: file.name,
            url: response.url
          }
        )
        console.log(this.form.fileList);
      } else {
        this.$message.warning(`上传失败`);
        // this.form.fileList.splice(this.form.fileList.length - 1, 1);
      }
      // fileList[0].response.url;

    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    getList() {
      // this.$modal.closeLoading();
      listCandidate(this.queryParams2).then(response => {
        this.candidateList2 = response.rows;
        if (this.candidateList2 != null) {
          this.form = this.candidateList2[0];
          if (this.form.ccompanyList == null || this.form.ccompanyList.length == 0) {
            this.form.ccompanyList.push(this.jobsData)
          }
          if (this.form.schoolList == null || this.form.schoolList.length == 0) {
            this.form.schoolList.push(this.schoolDate)
          }
          this.form.fileList = [];
          if (this.form.filePath != null && this.form.filePath != '') {
            this.form.fileListPath = this.form.filePath.split(",");
            for (let i = 0; i < this.form.fileListPath.length; i++) {
              this.form.fileList.push({
                name: this.form.fileListPath[i].substring(this.form.filePath.lastIndexOf('/') + 1),
                url: this.form.fileListPath[i]
              });
            }
          }
        }
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function() {
        return changeUserStatus(row.userId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {

    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getCVList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
      }).then(({ value }) => {
          resetUserPwd(row.userId, value).then(response => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        }).catch(() => {});
    },
    /** 分配角色操作 */
    handleAuthRole: function(row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fileList != null && this.form.fileList.length > 0) {
            this.form.filePath = this.form.fileList.join(",");
          }
          if (this.form.id != null) {
            updateCandidate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              const obj = { path: "/cand/candidate" };
              this.$tab.closeOpenPage(obj);
            });
          } else {
            // this.form['ccompanyList'] = this.ccompanyList;
            // this.form['schoolList'] = this.schoolList;
            addCandidate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              const obj = { path: "/cand/candidate" };
              this.$tab.closeOpenPage(obj);
              // this.open = false;
              // this.getList();
            });
          }
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  //去掉表格内的线
  table th,
  table td {
    /*border-bottom: none !important;*/
  }
  .el-table {
    .el-table__body {
      //-webkit-border-horizontal-spacing: 13px;  // 水平间距
      -webkit-border-vertical-spacing: 10px; // 垂直间距 设置的是行间距
    }
  }
  //去掉最下面的那一条线
  .el-table::before {
    height: 0px;
  }
  .customer-table .el-table__fixed-right::before,
  .el-table__fixed::before {
    width: 0;
  }
  .el-table .el-table__cell {
     border-radius: 10px;
     border: 1px solid #cccccc;
     padding: 0px 0;
  }
  .el-form-item {
    margin-bottom: 10px;
  }
  .el-table tbody tr:hover>td {
    border-radius: 10px;
    border: 1px solid #cccccc;
    background-color:#DE6 !important
    //修改成自己想要的颜色即可
  }
  el-input {
    width: 200px;
  }
</style>

